package com.example.limiting.taskmanager2;

import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Limiting on 2015/9/24.
 */
public class TaskFragment extends Fragment {
    public static final String ARG_PLANET_NUMBER = "planet_number";
    public static final String ARG_ACTION_NUMBER = "action_number";

    private TaskAdapter taskAdapter;
    private ListView taskList;

    private int planet_number;
    private int action_number;
    private Context mContext;
    public TaskFragment() {
        // Empty constructor required for fragment subclasses
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_task, container, false);
        planet_number = getArguments().getInt(ARG_PLANET_NUMBER);
        action_number = getArguments().getInt(ARG_ACTION_NUMBER);
        mContext = rootView.getContext();

        String task = getResources().getStringArray(R.array.tasks_array)[planet_number ];
        getActivity().setTitle(task);
        
        taskAdapter = new TaskAdapter(rootView.getContext(),R.layout.task_list_item);
        taskList = (ListView) rootView.findViewById(R.id.TaskList);

        new LoadListTask().execute(planet_number,action_number);
//        testSetData();
        return rootView;
    }

    private class TaskItemClickListener implements ListView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            selectTaskItem(view,position);
        }
    }

    private void selectTaskItem(View view,int position){
        TextView title = (TextView) view.findViewById(R.id.task_title);
//        Toast.makeText(getActivity(), title.getText().toString()+ position, Toast.LENGTH_SHORT).show();
//        Intent intent = new Intent();
//        intent.setClass(getActivity(),DetailActivity.class);
//        intent.putExtra("title", title.getText().toString());
//        intent.putExtra("start_time","起始时间");
//        intent.putExtra("end_time","结束时间");
//        intent.putExtra("type","种类");
//        intent.putExtra("content","详细信息");
//        intent.putExtra("planet_number",planet_number);
//        intent.putExtra("action_number",action_number);
//        startActivity(intent);
        new LoadDetailTask().execute(title.getTag().toString());
    }

    private class LoadListTask extends AsyncTask<Integer,Void,String>{

        @Override
        protected String doInBackground(Integer... params) {
            HttpHelper httpHelper = new HttpHelper(getActivity());
            String result = null;
            try {
                result = httpHelper.loadList(null,params[0],params[1]);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return result;
        }

        protected void onPostExecute(String result){
            if (result.isEmpty()){
                Toast.makeText(mContext,"网络状态不好，请重试！",Toast.LENGTH_SHORT).show();
            }else{
                JSONTokener jsonParser = new JSONTokener(result);
                try {
                    JSONObject body = (JSONObject) jsonParser.nextValue();
                    JSONArray jTasks = body.getJSONArray("data");
                    List<Task> tasks = new ArrayList<Task>();
                    for (int i = 0;i < jTasks.length();i++){
                        JSONObject jTask = jTasks.getJSONObject(i);
                        Task t = new Task(jTask.getString("taskTitle"),jTask.getString("startDate"),jTask.getString("endDate"),jTask.getString("taskId"));
                        tasks.add(t);
                    }
                    setData(tasks);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private void setData(List<Task> tasks){
        taskAdapter.addAll(tasks);

        taskList.setAdapter(taskAdapter);
        taskList.setOnItemClickListener(new TaskItemClickListener());
        taskList.deferNotifyDataSetChanged();
    }
    //for test use
    private void testSetData(){

        for (int i = 0;i < 20;i++){
            taskAdapter.add(new Task("test"+i,"123","321","123"));
        }
        taskList.setAdapter(taskAdapter);
        taskList.setOnItemClickListener(new TaskItemClickListener());
        taskList.deferNotifyDataSetChanged();
    }

    private class LoadDetailTask extends AsyncTask<String,Void,String>{
        @Override
        protected String doInBackground(String... params) {
            HttpHelper httpHelper = new HttpHelper(getActivity());
            String result = null;
            try {
                result = httpHelper.loadDetail(params[0]);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return result;
        }

        @Override
        protected void onPostExecute(String result) {
            if (result.isEmpty()){
                Toast.makeText(mContext,"网络状态不好，请重试！",Toast.LENGTH_SHORT).show();
            }else {
                Intent intent = new Intent();
                intent.setClass(getActivity(),DetailActivity.class);
                intent.putExtra("data", result);
                intent.putExtra("planet_number", planet_number);
                intent.putExtra("action_number",action_number);
                startActivity(intent);
            }
        }
    }
}

